package com.gingersoft.connect.utils

import android.util.Log
import com.gingersoft.connect.bean.MessageBean
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress

class MyWebSocketServer(address: InetSocketAddress) :
    WebSocketServer(address) {
    val TAG = "MyWebSocketServer"

    private val connections: HashSet<WebSocket> by lazy { HashSet() }

    override fun onOpen(conn: WebSocket, handshake: ClientHandshake?) {
        connections.add(conn)
        Log.e(TAG, "服務端被連接")
        conn.send("已連接")
    }

    override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
        connections.remove(conn)
        Log.e(TAG, "${conn?.remoteSocketAddress?.hostString}客戶端斷開連接")
    }

    override fun onMessage(conn: WebSocket?, message: String?) {
        Log.e(TAG, "收到消息：$message")
        // 有KDS主動獲取食品、沽清信息接口
        // RicePOS收到KDS要獲取食品的消息後，發送本地食品信息過去
        message?.let {
            val msg = GsonUtils.GsonToBean(message, MessageBean::class.java)
            // 创建一个协程作用域
            val scope = CoroutineScope(Dispatchers.IO)
            // 在协程作用域中异步处理消息
            scope.launch {
                Log.e(TAG, "開始處理消息:$msg")
                MsgParser.process(msg)?.let {
                    val gsonString = GsonUtils.GsonString(it)
                    Log.e(TAG, "處理結果:$gsonString")
                    // 接受到消息並處理後，將結果返回回去
                    conn?.send(gsonString)
                }
            }
        }
    }

    override fun onError(conn: WebSocket?, ex: Exception?) {
        Log.e(TAG, "服務器出錯: ${ex?.message}")
    }

    override fun onStart() {
        Log.e(TAG, "開啟")
    }

    fun callbackMsg(msg: String) {

    }

    fun sendMessage(msg: String) {
        connections.forEach {
            it.send(msg)
        }
    }
}